package ${package.ServiceImpl};

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import ${cfg.utilPackge}.QueryWrapperHelper;
import ${cfg.commonPackge}.PageParams;
import ${cfg.commonPackge}.PageResult;
import ${cfg.commonPackge}.AppResp;
import ${cfg.utilPackge}.OrikaBeanMapper;
import ${cfg.utilPackge}.BeanUtil;
import ${package.Mapper}.${entity}Mapper;
import ${cfg.voEntityPackage}.${entity}VO;
import ${package.Entity}.${entity};
import ${package.Service}.${entity}Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * ${table.comment!} Service 接口实现类
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
@Service("${'${entity}ServiceImpl'?uncap_first}4${cfg.module}")
@Slf4j
public class ${entity}ServiceImpl extends ServiceImpl<${entity}Mapper, ${entity}> implements ${entity}Service {

    @Autowired
    private ${entity}Mapper ${'${entity}'?uncap_first}Mapper;

    @Override
    public AppResp<PageResult<${entity}VO>> page(PageParams<${entity}VO> pageParams) {
        ${entity} ${'${entity}'?uncap_first} = OrikaBeanMapper.map(pageParams.getEntityParams(), ${entity}.class);
        QueryWrapper<${entity}> queryWrapper = new QueryWrapper<>();
        try {
            QueryWrapperHelper.getInstance().convert(${'${entity}'?uncap_first}, queryWrapper);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            log.error("分页查询参数转换错误", e);
        }

        IPage<${entity}> params = new Page<>();
        params.setCurrent(pageParams.getPageNum());
        params.setSize(pageParams.getPageSize());

        IPage<${entity}> pageResultTmp = ${'${entity}'?uncap_first}Mapper.selectPage(params, queryWrapper);
        List<${entity}VO> ${'${entity}'?uncap_first}VOs = OrikaBeanMapper.mapAsList(pageResultTmp.getRecords(), ${entity}VO.class);

        PageResult<${entity}VO> pr = new PageResult<>();
        pr.setCurrent(pageResultTmp.getCurrent());
        pr.setPages(pageResultTmp.getPages());
        pr.setSize(pageResultTmp.getSize());
        pr.setTotal(pageResultTmp.getTotal());
        pr.setRecords(${'${entity}'?uncap_first}VOs);
        return AppResp.success(pr);
    }

    @Override
    public AppResp<${entity}VO> queryById(Long ${'${entity}'?uncap_first}Id) {
        QueryWrapper<${entity}> queryWrapper = new QueryWrapper<>();

        ${entity} ${'${entity}'?uncap_first} = ${'${entity}'?uncap_first}Mapper.selectById(${'${entity}'?uncap_first}Id);
        if (ObjectUtils.isEmpty(${'${entity}'?uncap_first})) {
            return AppResp.error("您查询的记录不存在，操作失败");
        }

        ${entity}VO ${'${entity}VO'?uncap_first} = OrikaBeanMapper.map(${'${entity}'?uncap_first}, ${entity}VO.class);
        return AppResp.success(${'${entity}VO'?uncap_first});
    }

    @Override
    public AppResp<Void> add(${entity}VO ${'${entity}'?uncap_first}VO) {
        ${entity} ${'${entity}'?uncap_first} = OrikaBeanMapper.map(${'${entity}'?uncap_first}VO, ${entity}.class);
        // TODO 如果插入前需要根据某个属性判断对象是否存在，请修改下面代码：
        /*
        List<${entity}> core${entity}s = ${'${entity}'?uncap_first}Mapper.selectList(new QueryWrapper<${entity}>().lambda()
            .eq(${entity}::getAccount, ${'${entity}'?uncap_first}.getAccount()));
        if (!ObjectUtils.isEmpty(core${entity}s)) {
            return AppResp.error("已存在[" + ${'${entity}'?uncap_first}.getAccount() + "]记录，添加失败");
        }
        */
        ${'${entity}'?uncap_first}.setDeleteFlag(false);
        ${'${entity}'?uncap_first}.setCreateAt(LocalDateTime.now());
        ${'${entity}'?uncap_first}.setCreateBy("admin");
        return ${'${entity}'?uncap_first}.insert() ? AppResp.success() : AppResp.error("操作失败，请重试");
    }

    @Override
    public AppResp<Void> delById(Long ${'${entity}'?uncap_first}Id) {
        ${entity} ${'${entity}'?uncap_first} = ${'${entity}'?uncap_first}Mapper.selectById(${'${entity}'?uncap_first}Id);
        if (ObjectUtils.isEmpty(${'${entity}'?uncap_first})) {
            return AppResp.error("删除的对象不存在，操作失败");
        }
        ${'${entity}'?uncap_first}.setDeleteFlag(true);
        ${'${entity}'?uncap_first}.setUpdateAt(LocalDateTime.now());
        // TODO 需要改为当前登录的人
        ${'${entity}'?uncap_first}.setUpdateBy("admin");
        return ${'${entity}'?uncap_first}.updateById() ? AppResp.success() : AppResp.error("操作失败，请重试");

        // 下面是真实删除的代码，可以根据需要放开
        /*
        int i = ${'${entity}'?uncap_first}Mapper.deleteById(${'${entity}'?uncap_first}Id);
        return i > 0 ? AppResp.success() : AppResp.error("操作失败，没有该记录");
        */
    }

    @Override
    public AppResp<Void> modify(${entity}VO ${'${entity}'?uncap_first}VO) {
        ${entity} ${'${entity}'?uncap_first} = OrikaBeanMapper.map(${'${entity}'?uncap_first}VO, ${entity}.class);

        <#assign x = false>
        <#list table.fields as field>
            <#if field.keyFlag && field.keyIdentityFlag>
                <#assign x = true />
        ${entity} exist${entity} = ${'${entity}'?uncap_first}Mapper.selectById(${'${entity}'?uncap_first}.get${'${field.propertyName}'?cap_first}());
        if (ObjectUtils.isEmpty(exist${entity})) {
            return AppResp.error("不存在[" + ${'${entity}'?uncap_first}.get${'${field.propertyName}'?cap_first}() + "]记录，操作失败");
        }
                <#break>
            </#if>
        </#list>
        <#if !x>
        // TODO 没有主键，无法查找对象是否已存在，请修改下面代码进行对象查找
        /*
        ${entity} exist${entity} = ${'${entity}'?uncap_first}Mapper.selectById(${'${entity}'?uncap_first}.getTid());
        if (ObjectUtils.isEmpty(exist${entity})) {
            return AppResp.error("不存在[" + ${'${entity}'?uncap_first}.getTid() + "]记录，操作失败");
        }
        */
        </#if>

        try {
            BeanUtil.merge(${'${entity}'?uncap_first}, exist${entity});
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return AppResp.error("操作失败，"+e.getMessage());
        }

        exist${entity}.setUpdateAt(LocalDateTime.now());
        exist${entity}.setUpdateBy("admin");
        return exist${entity}.updateById() ? AppResp.success() : AppResp.error("操作失败，请重试");
    }
}
